<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.3" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png?v=5.1.3">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png?v=5.1.3">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.3" color="#222">





  <meta name="keywords" content="加密," />





  <link rel="alternate" href="/atom.xml" title="大牙的杂货铺" type="application/atom+xml" />






<meta name="description" content="TCP/IP 安全因素 数据机密性  保证数据密文传输，中间人不能破解数据真实内容。  常见的不机密通信：ftp、http、smtp、telnet。这些协议的通信过程中都是明文传输，无法保证数据的机密性。    数据完整性  数据是否被篡改：入侵者不能使用假数据代替合法数据，否则数据将丧失完整性。   身份验证  验证">
<meta name="keywords" content="加密">
<meta property="og:type" content="article">
<meta property="og:title" content="加密类型及算法">
<meta property="og:url" content="http://linuxgeeks.github.io/2016/01/31/2016-01-31-081037-加密类型及算法/index.html">
<meta property="og:site_name" content="大牙的杂货铺">
<meta property="og:description" content="TCP/IP 安全因素 数据机密性  保证数据密文传输，中间人不能破解数据真实内容。  常见的不机密通信：ftp、http、smtp、telnet。这些协议的通信过程中都是明文传输，无法保证数据的机密性。    数据完整性  数据是否被篡改：入侵者不能使用假数据代替合法数据，否则数据将丧失完整性。   身份验证  验证身份的真实性，防止非法者冒充。    加密技术及算法对称加密简介 加密（encr">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-01-30T14:14:02.965Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="加密类型及算法">
<meta name="twitter:description" content="TCP/IP 安全因素 数据机密性  保证数据密文传输，中间人不能破解数据真实内容。  常见的不机密通信：ftp、http、smtp、telnet。这些协议的通信过程中都是明文传输，无法保证数据的机密性。    数据完整性  数据是否被篡改：入侵者不能使用假数据代替合法数据，否则数据将丧失完整性。   身份验证  验证身份的真实性，防止非法者冒充。    加密技术及算法对称加密简介 加密（encr">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Muse',
    version: '5.1.3',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":true},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://linuxgeeks.github.io/2016/01/31/2016-01-31-081037-加密类型及算法/"/>





  <title>加密类型及算法 | 大牙的杂货铺</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
	
	<a href="https://github.com/mengdaya"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://camo.githubusercontent.com/38ef81f8aca64bb9a64448d0d70f1308ef5341ab/68747470733a2f2f73332e616d617a6f6e6177732e636f6d2f6769746875622f726962626f6e732f666f726b6d655f72696768745f6461726b626c75655f3132313632312e706e67" alt="Fork me on GitHub" data-canonical-src="https://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png"></a>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">大牙的杂货铺</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-commonweal">
          <a href="/404/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-heartbeat"></i> <br />
            
            公益404
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://linuxgeeks.github.io/2016/01/31/2016-01-31-081037-加密类型及算法/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="孟庆宇">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="大牙的杂货铺">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">加密类型及算法</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2016-01-31T08:10:37+08:00">
                2016-01-31
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Security/" itemprop="url" rel="index">
                    <span itemprop="name">Security</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"> 本文总阅读量</i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  3,242
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  12
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h4 id="TCP-IP-安全因素"><a href="#TCP-IP-安全因素" class="headerlink" title="TCP/IP 安全因素"></a>TCP/IP 安全因素</h4><ul>
<li><p>数据机密性</p>
<ul>
<li><p>保证数据密文传输，中间人不能破解数据真实内容。</p>
</li>
<li><p>常见的不机密通信：ftp、http、smtp、telnet。这些协议的通信过程中都是明文传输，无法保证数据的机密性。</p>
</li>
</ul>
</li>
<li><p>数据完整性</p>
<ul>
<li>数据是否被篡改：入侵者不能使用假数据代替合法数据，否则数据将丧失完整性。</li>
</ul>
</li>
<li><p>身份验证</p>
<ul>
<li>验证身份的真实性，防止非法者冒充。</li>
</ul>
</li>
</ul>
<h4 id="加密技术及算法"><a href="#加密技术及算法" class="headerlink" title="加密技术及算法"></a>加密技术及算法</h4><h5 id="对称加密"><a href="#对称加密" class="headerlink" title="对称加密"></a>对称加密</h5><h6 id="简介"><a href="#简介" class="headerlink" title="简介"></a>简介</h6><ul>
<li><p>加密（encryption）与解密（decryption）使用的是同样的密钥（secret key），密码学中叫对称加密算法。</p>
</li>
<li><p>保证数据的机密性。</p>
</li>
<li><p>解密方事先必须知道加密密钥，否则无法解密。</p>
</li>
</ul>
<h6 id="算法"><a href="#算法" class="headerlink" title="算法"></a>算法</h6><ul>
<li>常用的算法有：DES、3DES、TDEA、Blowfish、RC2、RC4、RC5、IDEA、SKIPJACK、AES等。</li>
</ul>
<h6 id="优势"><a href="#优势" class="headerlink" title="优势"></a>优势</h6><ul>
<li>算法公开、计算量小、加密速度快、加密效率高。</li>
</ul>
<h6 id="缺点"><a href="#缺点" class="headerlink" title="缺点"></a>缺点</h6><ul>
<li><p>在数据传送前，发送方和接收方必须商定好密钥，然后使双方都能保存好密钥。</p>
</li>
<li><p>双方使用同样的密钥，安全性无法得到保证。若一方的密钥被泄露，那么加密信息就不安全。</p>
</li>
<li><p>每对用户每次使用对称加密算法时，都需要使用其他人不知道的唯一密钥，使得收、发双方所拥有的钥匙数量巨大，密钥管理成为双方的负担。</p>
</li>
</ul>
<h5 id="单向加密"><a href="#单向加密" class="headerlink" title="单向加密"></a>单向加密</h5><h6 id="简介-1"><a href="#简介-1" class="headerlink" title="简介"></a>简介</h6><ul>
<li><p>不可逆加密，在加密过程中不使用密钥，明文由系统加密算法处理成密文，密文无法解密。</p>
</li>
<li><p>提取数据的指纹及特征码，用于校验，保证数据的完整性。 </p>
</li>
</ul>
<h6 id="特征"><a href="#特征" class="headerlink" title="特征"></a>特征</h6><ul>
<li><p>输入一样，输出必然一样</p>
</li>
<li><p>雪崩效应：输入的一点改变，引起结果的巨大改变，常用于防暴力破解。</p>
</li>
<li><p>定长输出：无论输入的长度多长，输出的结果都一样长。</p>
</li>
<li><p>不可逆：无法根据特征码还原数据。</p>
</li>
<li><p>无法进行身份验证和保证数据的机密性。</p>
</li>
</ul>
<h6 id="算法-1"><a href="#算法-1" class="headerlink" title="算法"></a>算法</h6><ul>
<li>MD4</li>
<li>MD5 message-digest algorithm 5（信息-摘要算法，输出结果固定长度128bit</li>
<li>SHA1：secure hash algorithm（安全散列算法）,输出结果固定长度160bit</li>
<li>SHA192，SHA256，SHA384</li>
<li>CRC-32 不加密，只提供校验功能</li>
</ul>
<h6 id="实现过程"><a href="#实现过程" class="headerlink" title="实现过程"></a>实现过程</h6><ul>
<li><p>发送方为了防止明文数据Data被其他人篡改，对数据使用单向加密算法，计算得到特征码A。</p>
</li>
<li><p>发送方将数据Data和特征码A一起发送给接收方。</p>
</li>
<li><p>接收方收到数据Data和特征码A。对数据Data使用相同的单向加密算法，计算出一个特征码B。</p>
</li>
<li><p>如果特征码A和B相同，则说明数据是完整的；否则数据被篡改，丧失完整性。</p>
</li>
</ul>
<h6 id="遗留问题"><a href="#遗留问题" class="headerlink" title="遗留问题"></a>遗留问题</h6><ul>
<li><p>如果发送方在传递数据Data给接收方的过程中时，遭到中间人攻击，导致数据都被中间人截获。</p>
</li>
<li><p>中间人冒充发送方，对数据Data也进行单向加密算法，计算出特征码C，再将Data和特征码C一起发送给接收方。</p>
</li>
<li><p>接收方收到数据后对其进行单向加密算法，计算出的特征码和C一样。虽然特征码是相同的，但这并不是真实的发送方发来的数据。</p>
</li>
<li><p>接收方最终无法判断数据的来源，陷入身份验证的困境，因此引入了密钥交换。</p>
</li>
</ul>
<h6 id="密钥交换"><a href="#密钥交换" class="headerlink" title="密钥交换"></a>密钥交换</h6><ul>
<li><p>互联网密钥交换：Internet Key Exchange，简称IKE</p>
</li>
<li><p>基于Diffie-Hellman协议协商生成密码。</p>
</li>
<li><p>实现双方使眼色交换密钥，而且密钥本身不在互联网上传播</p>
</li>
</ul>
<h6 id="IKE大致原理"><a href="#IKE大致原理" class="headerlink" title="IKE大致原理"></a>IKE大致原理</h6><ul>
<li><p>主机A和B协商选择两个数字：P，g（大素数，生成器数）</p>
</li>
<li><p>A在本机随机选择一个数字x，B在本机随机选择一个数字y。x只有A知道，y只有B知道，且x和y不在互联网传输</p>
</li>
<li><p>A将g^x%P计算结果Ra发送给B</p>
</li>
<li><p>B将g^y%P计算结果Rb发送给A</p>
<ul>
<li><p>互联网中的用户能看到的数字有四个：P，g，Ra，Rb</p>
</li>
<li><p>由于离散对数的原理，根据暴露的4个数字几乎不可能推算出x和y的值</p>
</li>
</ul>
</li>
<li><p>A主机对Rb取x次方：(g^y%P)^x=g^yx%P</p>
</li>
<li><p>B主机对Ra取y次方：(g^x%P)^y=g^xy%P</p>
</li>
<li><p>二者结果相同进而生成密钥，密钥交换问题解决。</p>
</li>
</ul>
<h6 id="陷入困境"><a href="#陷入困境" class="headerlink" title="陷入困境"></a>陷入困境</h6><ul>
<li><p>A和B已经事先约定好数字后传输不需再次事先商定数字P和g，每次发送数据只需都进行一次计算，进行一次密钥交换即可。因此保证了身份验证。</p>
</li>
<li><p>但是，如果A和B从未见过面，第一次进行传输时，在商定数字的过程中遭到中间人攻击，则来源身份就可能被冒充，B又再次陷入身份验证的僵局。</p>
</li>
<li><p>要完成用户的身份验证，就需要使用非对称加密。</p>
</li>
</ul>
<h5 id="非对称加密"><a href="#非对称加密" class="headerlink" title="非对称加密"></a>非对称加密</h5><h6 id="简介-2"><a href="#简介-2" class="headerlink" title="简介"></a>简介</h6><ul>
<li><p>非对称加密也叫公钥加密。</p>
</li>
<li><p>公钥与私钥是一对，如果用公钥对数据进行加密，只有用对应的私钥才能解密；如果用私钥对数据进行加密，那么只有用对应的公钥才能解密。因为加密和解密使用的是两个不同的密钥，所以叫作非对称加密。</p>
</li>
</ul>
<h6 id="密钥对"><a href="#密钥对" class="headerlink" title="密钥对"></a>密钥对</h6><ul>
<li><p>公钥：public key，从私钥中抽出的一段特征，只能用与之对应的私钥解密。</p>
</li>
<li><p>私钥：private key，只能用与之对应的公钥解密。</p>
</li>
<li><p>A用B的公钥加密数据，传输后的数据只有B用自己的私钥才能解开，以此保证了数据的机密性</p>
</li>
<li><p>A用自己的私钥加密数据，私钥只有A知道，只要B用A的公钥能解密数据就说明是数据A加密的，以此保证了身份验证</p>
</li>
</ul>
<h6 id="密钥对原则"><a href="#密钥对原则" class="headerlink" title="密钥对原则"></a>密钥对原则</h6><ul>
<li><p>一个公钥对应一个私钥。</p>
</li>
<li><p>让大家都知道的是公钥，不告诉大家只有自己知道的是私钥。  </p>
</li>
<li><p>如果用其中一个密钥加密数据，则只有对应的那个密钥才可以解密。   </p>
</li>
<li><p>如果用其中一个密钥可以进行解密数据，则该数据必然是对应的那个密钥进行的加密。    </p>
</li>
<li><p>非对称密钥的主要应用就是公钥加密和公钥认证，而公钥加密的过程和公钥认证的过程是不一样的。</p>
</li>
</ul>
<h6 id="工作原理"><a href="#工作原理" class="headerlink" title="工作原理"></a>工作原理</h6><ul>
<li><p>A和B通信，双方事先产生一对用于自己加密和解密的公钥和私钥。</p>
</li>
<li><p>A的私钥保密，公钥公开；B的私钥保密，公钥发送给A。</p>
</li>
<li><p>A给B发送数据</p>
<ul>
<li><p>为了保证数据完整性，使用单向加密算法计算出数据的特征码。将特征码附着在数据后发送给B。</p>
<ul>
<li><p>中间人C获取数据后，使用A的公钥解密得到了特征码。</p>
</li>
<li><p>对数据进行篡改后，使用单向加密算法算出来的特征码无法还原成A计算出的特征码。</p>
</li>
</ul>
</li>
<li><p>为了保证身份验证，防止特征码被中间人冒充，A使用自己的私钥对特征码进行加密。</p>
<ul>
<li><p>中间人C截获数据后(即便无任何修改)，使用自己的私钥对A计算的特征码加密，冒充A将截获的数据及自己私钥加密后的特征码发送给B。</p>
</li>
<li><p>B收到C（冒充A）发来的数据，此时仍然认为发送方是A。</p>
</li>
<li><p>B使用A的公钥却无法解密冒充者C私钥加密的特征码。</p>
</li>
</ul>
</li>
<li><p>为了保证数据的机密性，A使用B的公钥对所有数据加密。</p>
</li>
</ul>
</li>
<li><p>B收到数据后</p>
<ul>
<li><p>使用自己的私钥解密所有数据。</p>
</li>
<li><p>使用A的公钥成功解密得到了特征码，则验证了A的身份。</p>
<ul>
<li>只有A私钥加密的数据发过来才能用A的公钥解密。因为A的私钥只有A一个人有。 </li>
</ul>
</li>
<li><p>使用单向加密算法计算数据的特征码，与发送过来解密后的特征码作比较，如果相同则说明数据完好无损。</p>
</li>
<li><p>用自己的私钥解密A使用B的公钥加密后发送过来的数据。其他人都无法解密，因为只有B才有自己的私钥。保证了数据的机密性。</p>
</li>
</ul>
</li>
</ul>
<h6 id="加密算法"><a href="#加密算法" class="headerlink" title="加密算法"></a>加密算法</h6><ul>
<li>RSA：可进行数据加密、解密、签名</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">openssl genrsa -out private.key 1024</span><br><span class="line"><span class="comment"># 生成一个私钥，密钥长度为1024bit</span></span><br><span class="line"></span><br><span class="line">openssl rsa -<span class="keyword">in</span> private.key -pubout -out pub.key</span><br><span class="line"><span class="comment"># 通过密钥文件private.key 提取公钥</span></span><br><span class="line">      </span><br><span class="line"><span class="built_in">echo</span> -n <span class="string">"123456"</span> | openssl rsautl -encrypt -inkey pub.key -pubin &gt;encode.result</span><br><span class="line"><span class="comment"># 使用公钥加密信息</span></span><br><span class="line">     </span><br><span class="line">cat encode.result | openssl rsautl -decrypt  -inkey private.key </span><br><span class="line"><span class="comment"># 使用私钥解密信息</span></span><br></pre></td></tr></table></figure>
<ul>
<li>DSA：只能用于数字签名及其认证</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">openssl dsaparam -out dsaparam.pem 1024</span><br><span class="line">openssl gendsa -out privkey.pem dsaparam.pem</span><br><span class="line"><span class="comment"># 生成一个密钥(私钥)</span></span><br><span class="line"></span><br><span class="line">openssl dsa -<span class="keyword">in</span> privkey.pem -out pubkey.pem -pubout</span><br><span class="line">rm -fr dsaparam.pem </span><br><span class="line"><span class="comment"># 生成公钥</span></span><br><span class="line"> </span><br><span class="line"><span class="built_in">echo</span> -n <span class="string">"123456"</span> | openssl dgst -dss1 -sign privkey.pem &gt; sign.result</span><br><span class="line"><span class="comment"># 使用私钥签名</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">echo</span> -n <span class="string">"123456"</span> | openssl dgst -dss1 -verify pubkey.pem -signature sign.result</span><br><span class="line"><span class="comment"># 使用公钥验证</span></span><br></pre></td></tr></table></figure>
<ul>
<li><p>在DSA数字签名和认证中，发送者使用自己的私钥对文件或消息进行签名，接受者收到消息后使用发送者的公钥来验证签名的真实性。</p>
</li>
<li><p>DSA算法和RSA不同之处在于它不能用作加密和解密，也不能进行密钥交换，只用于签名，因此速度比RSA要快很多。</p>
</li>
</ul>
<h6 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h6><ul>
<li><p>加密速度慢，比对称加密慢3个数量级1000倍（一个数量级：10倍）</p>
</li>
<li><p>一般不用于加密大量数据，主要用于实现用户认证和帐号信息加密。</p>
</li>
</ul>
<h5 id="公钥验证"><a href="#公钥验证" class="headerlink" title="公钥验证"></a>公钥验证</h5><ul>
<li><p>非对称加密过程中，无法保证公钥的来源的可靠性，因此引入了第三方认证机构。</p>
</li>
<li><p>双方在通信时都出示证件，这个证件由某个权威机构发放，只要验证证件内的有效信息就可以验证对方的身份。</p>
</li>
<li><p>为了防止在发证的时候出现中间人现欺骗，一些操作系统在安装时就已经将一些权威的发证机构的证书放在系统里了。</p>
</li>
</ul>
<h4 id="数字证书认证"><a href="#数字证书认证" class="headerlink" title="数字证书认证"></a>数字证书认证</h4><ul>
<li><p>CA(Certficate Authority)，数字证书认证中心，是整个网上电子交易安全的关键环节。它主要负责产生、分配并管理所有参与网上交易的实体所需的身份认证数字证书。</p>
</li>
<li><p>PKI：Public Key Infrastructure（公钥基础设施）。CA证书颁发机构，双方在通信时都出示证件，这个证件由某个权威机构发放，只需要验证证件内的有效信息</p>
</li>
<li><p>为了验证公钥发送方的合法性，因此有了证书颁发机构（要自己事先为自己颁发一个证书）</p>
</li>
<li><p>证书的格式：X509，PKCS</p>
</li>
<li><p>证书吊销列表：CRL(Certificate Revocation List)</p>
</li>
</ul>
<h4 id="三重验证"><a href="#三重验证" class="headerlink" title="三重验证"></a>三重验证</h4><blockquote>
<p>假设A和B彼此间是可靠的彼此认证的通信。即A和B通过CA机构颁发的证书彼此认可对方的公钥。</p>
</blockquote>
<ul>
<li><p>A和B通信，双方事先产生一对用于自己加密和解密的公钥和私钥。</p>
</li>
<li><p>A给B发送数据</p>
<ul>
<li><p>事先获取B的公钥。</p>
</li>
<li><p>A和B基于DH协议，互相协商后生成两个数字（P，g）</p>
</li>
<li><p>为了保证数据的完整性，使用单向加密算法得到数据的特征码。将特征码附着在数据后。</p>
</li>
<li><p>为了保证身份验证，防止特征码被中间人冒充，A使用自己的私钥对特征码进行加密。</p>
</li>
<li><p>为了保证数据的机密性，A在本机生成一段随机数字(x)当作解开所有数据的对称密码，对数据加密，这个密码发送前只有A知道。</p>
</li>
<li><p>A使用B的公钥将对称密码加密，将加密的数据、对称密码发送给B。</p>
</li>
</ul>
</li>
<li><p>B收到数据后</p>
<ul>
<li><p>使用自己的私钥解密数据，得到了A的对称密码和对称密码加密的数据。使用A的对称密码解密数据。保证了数据机密性。</p>
<ul>
<li>中间人即便获得数据也无法解开对称密码，因为对称密码使用的是B的公钥加密，只有B的私钥才能解开。对称密码加密后的数据及特征码也无从得知。</li>
</ul>
</li>
<li><p>使用A的公钥解密得到（A私钥加密的）特征码。解密成功，则A的身份得到验证。</p>
</li>
<li><p>使用单向加密算法计算数据的特征码与解密得到的特征码作比较，如果相同则说明数据完好无损。</p>
</li>
</ul>
</li>
</ul>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>有钱任性，请我吃包辣条</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.jpg" alt="孟庆宇 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="孟庆宇 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    孟庆宇
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="http://linuxgeeks.github.io/2016/01/31/2016-01-31-081037-加密类型及算法/" title="加密类型及算法">http://linuxgeeks.github.io/2016/01/31/2016-01-31-081037-加密类型及算法/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/加密/" rel="tag"><i class="fa fa-tag"></i> 加密</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2016/01/15/2016-01-15-160358-使用whiptail创建交互式shell对话框/" rel="next" title="使用whiptail创建交互式shell对话框">
                <i class="fa fa-chevron-left"></i> 使用whiptail创建交互式shell对话框
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2016/02/01/2016-02-01-105633-OpenSSL/" rel="prev" title="OpenSSL">
                OpenSSL <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        
  <div class="bdsharebuttonbox">
    <a href="#" class="bds_tsina" data-cmd="tsina" title="分享到新浪微博"></a>
    <a href="#" class="bds_douban" data-cmd="douban" title="分享到豆瓣网"></a>
    <a href="#" class="bds_sqq" data-cmd="sqq" title="分享到QQ好友"></a>
    <a href="#" class="bds_qzone" data-cmd="qzone" title="分享到QQ空间"></a>
    <a href="#" class="bds_weixin" data-cmd="weixin" title="分享到微信"></a>
    <a href="#" class="bds_tieba" data-cmd="tieba" title="分享到百度贴吧"></a>
    <a href="#" class="bds_twi" data-cmd="twi" title="分享到Twitter"></a>
    <a href="#" class="bds_fbook" data-cmd="fbook" title="分享到Facebook"></a>
    <a href="#" class="bds_more" data-cmd="more"></a>
    <a class="bds_count" data-cmd="count"></a>
  </div>
  <script>
    window._bd_share_config = {
      "common": {
        "bdText": "",
        "bdMini": "2",
        "bdMiniList": false,
        "bdPic": ""
      },
      "share": {
        "bdSize": "16",
        "bdStyle": "0"
      },
      "image": {
        "viewList": ["tsina", "douban", "sqq", "qzone", "weixin", "twi", "fbook"],
        "viewText": "分享到：",
        "viewSize": "16"
      }
    }
  </script>

<script>
  with(document)0[(getElementsByTagName('head')[0]||body).appendChild(createElement('script')).src='//bdimg.share.baidu.com/static/api/js/share.js?cdnversion='+~(-new Date()/36e5)];
</script>

      
    </div>
  </div>


          </div>
          


          
  


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
      <div id="sidebar-dimmer"></div>
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="孟庆宇" />
            
              <p class="site-author-name" itemprop="name">孟庆宇</p>
              <p class="site-description motion-element" itemprop="description">书山有路勤为径，学海无涯苦作舟</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">109</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">56</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          <div class="links-of-author motion-element">
            
              
                <span class="links-of-author-item">
                  <a href="https://github.com/mengdaya" target="_blank" title="GitHub">
                    
                      <i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  <a href="mailto:yourname@gmail.com" target="_blank" title="E-Mail">
                    
                      <i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            
          </div>

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-globe"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.ibm.com/developerworks/cn/" title="IBM developerWorks" target="_blank">IBM developerWorks</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://iissnan.com/progit/" title="Pro Git" target="_blank">Pro Git</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.freeoa.net/index/" title="freeOA" target="_blank">freeOA</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ttlsa.com/" title="运维生存时间" target="_blank">运维生存时间</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.361way.com/" title="运维之路" target="_blank">运维之路</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.yiibai.com/" title="易百教程" target="_blank">易百教程</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.centoscn.com/" title="CentOS中文站" target="_blank">CentOS中文站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.linuxprobe.com/" title="Linux就该这么学" target="_blank">Linux就该这么学</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.netingcn.com/" title="网络进行时" target="_blank">网络进行时</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://www.ruanyifeng.com/blog/" title="阮一峰的网络日志" target="_blank">阮一峰的网络日志</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.liaoxuefeng.com" title="廖雪峰的官方网站" target="_blank">廖雪峰的官方网站</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yihui.name/cn/" title="谢益辉的博客" target="_blank">谢益辉的博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://coolshell.cn" title="酷壳" target="_blank">酷壳</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#TCP-IP-安全因素"><span class="nav-number">1.</span> <span class="nav-text">TCP/IP 安全因素</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#加密技术及算法"><span class="nav-number">2.</span> <span class="nav-text">加密技术及算法</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#对称加密"><span class="nav-number">2.1.</span> <span class="nav-text">对称加密</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#简介"><span class="nav-number">2.1.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#算法"><span class="nav-number">2.1.2.</span> <span class="nav-text">算法</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#优势"><span class="nav-number">2.1.3.</span> <span class="nav-text">优势</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#缺点"><span class="nav-number">2.1.4.</span> <span class="nav-text">缺点</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#单向加密"><span class="nav-number">2.2.</span> <span class="nav-text">单向加密</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#简介-1"><span class="nav-number">2.2.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#特征"><span class="nav-number">2.2.2.</span> <span class="nav-text">特征</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#算法-1"><span class="nav-number">2.2.3.</span> <span class="nav-text">算法</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#实现过程"><span class="nav-number">2.2.4.</span> <span class="nav-text">实现过程</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#遗留问题"><span class="nav-number">2.2.5.</span> <span class="nav-text">遗留问题</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#密钥交换"><span class="nav-number">2.2.6.</span> <span class="nav-text">密钥交换</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#IKE大致原理"><span class="nav-number">2.2.7.</span> <span class="nav-text">IKE大致原理</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#陷入困境"><span class="nav-number">2.2.8.</span> <span class="nav-text">陷入困境</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#非对称加密"><span class="nav-number">2.3.</span> <span class="nav-text">非对称加密</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#简介-2"><span class="nav-number">2.3.1.</span> <span class="nav-text">简介</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#密钥对"><span class="nav-number">2.3.2.</span> <span class="nav-text">密钥对</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#密钥对原则"><span class="nav-number">2.3.3.</span> <span class="nav-text">密钥对原则</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#工作原理"><span class="nav-number">2.3.4.</span> <span class="nav-text">工作原理</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#加密算法"><span class="nav-number">2.3.5.</span> <span class="nav-text">加密算法</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#特点"><span class="nav-number">2.3.6.</span> <span class="nav-text">特点</span></a></li></ol></li><li class="nav-item nav-level-5"><a class="nav-link" href="#公钥验证"><span class="nav-number">2.4.</span> <span class="nav-text">公钥验证</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#数字证书认证"><span class="nav-number">3.</span> <span class="nav-text">数字证书认证</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#三重验证"><span class="nav-number">4.</span> <span class="nav-text">三重验证</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">文章总结于网络，转载请注明出处</span>

  
</div>









        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user">本站访客</i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye">本站总访问量</i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>

  
  <script type="text/javascript" src="true"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.3"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.3"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.3"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.3"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.3"></script>



  


  




	





  





  








  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  

  

  

  

</body>
</html>
